package com.chen.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chen.blog.common.api.CommonResult;
import com.chen.blog.common.constant.MessageConstant;
import com.chen.blog.model.Admin;
import com.chen.blog.mapper.AdminMapper;
import com.chen.blog.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.blog.vo.PwdVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chen
 * @since 2022-01-24
 */
@Service
@Transactional
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;

    /**
     * 根据用户名获取用户功能实现
     *
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
    }

    /**
     * 更新用户密码功能实现
     *
     * @param pwdVo
     * @return
     */
    @Override
    public CommonResult updatePwd(PwdVo pwdVo) {
        Admin admin = adminMapper.selectById(pwdVo.getId());
        if (passwordEncoder.matches(pwdVo.getOldPwd(), admin.getPassword())) {
            admin.setPassword(passwordEncoder.encode(pwdVo.getNewPwd()));
            if (adminMapper.updateById(admin) == 1) {
                return CommonResult.success(MessageConstant.UPDATE_POSITION_SUCCESS);
            }
            return CommonResult.error(MessageConstant.UPDATE_POSITION_FAIL);
        }
        return CommonResult.error(MessageConstant.PWD_FAIL);
    }
}
